#include <stdio.h>
#include <sys/socket.h>
#include <string.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <errno.h>
#include <unistd.h>
#include <string>
using std::string;

#define MAX_LEN 4096
int main()
{
    int listen_fd, conn_fd;

    //--------------get bind fd--------------
    listen_fd = socket(AF_INET, SOCK_STREAM, 0);
    if(listen_fd == -1) {
        printf("creat socket failed.\n");
        return 0;
    }

    //----------------init struct sockaddt to bind--------------
    struct sockaddr_in addr;
    memset(&addr, 0, sizeof(addr));
    //AF_INET is the type of ipv4, and AF_INET6 is the type of ipv6
    addr.sin_family = AF_INET;
    //Converts a string to a network byte order binary address
    int ret = inet_pton(AF_INET, "0.0.0.0", (void*)&(addr.sin_addr));
    if(ret != 1) {
        printf("get network byte order binary address failed.\n");
        return 0;
    } else {
        printf("inet_pton ip address: 0x%x\n", addr.sin_addr.s_addr);
    }

    //---------------conver port to Network byte order----------
    uint16_t port = 6666;
    addr.sin_port = htons(port);
    printf("port:%u\n", addr.sin_port);

    //-----------bind addresss--------------
    ret = bind(listen_fd, (struct sockaddr*)&addr, sizeof(addr));
    if(ret < 0) {
        printf("bind ip:0.0.0.0, port:%u failed, erron:%d", 
                port, errno);
        close(listen_fd);
        return 0;
    }

    //--------set listend---------
    int backlog = 5;//the connect number to listen_fd;
    ret = listen(listen_fd, backlog);
    if(ret < 0) {
        printf("listen scoket failed, errno:%d\n", errno);
        close(listen_fd);
        return 0;
    }

    //-------------accept and read messag-----------
    char buf[MAX_LEN] = {0};
    while(1) {
        //accept other client to connect
        //do not save the client address, so use NULL
        conn_fd = accept(listen_fd, NULL, NULL);
        if(conn_fd < 0) {
            printf("accept failed, errno:%d\n", errno);
            break;
        }

        do{
            if(recv(conn_fd, buf, MAX_LEN, 0) < 0) {
                printf("recv msg failed, errno:%d\n", errno);
                break;
            }
            printf("get msg :%s\n", buf);
			
			string send_str = "success";
			if(send(conn_fd, send_str.c_str(), send_str.size() + 1, 0) < 0){
				printf("send msg failed, errno:%d\n", errno);
				break;
			}
        }while(false);
    }

    if(listen_fd > 0){
        close(listen_fd);
    }
    if(conn_fd >= 0) {
        close(conn_fd);
    }
    return 0;
}
